#!/bin/bash
# *************************************
# * 功能: Shell一键定制linux系统软件源
# * 作者: 王树森
# * 联系: wangshusen@sswang.com
# * 版本: 2025-06-09
# *************************************

# 检查root权限
[ "$(id -u)" -ne 0 ] && { echo "请使用root权限运行"; exit 1; }

# 选择操作系统
echo "该脚本同时支持一键部署如下系统的软件源: "
echo "1) Rocky Linux 9"
echo "2) Ubuntu 24.04"
echo "----------------------------------------"
source /etc/os-release
[ "${ID}" == "rocky" ] && os="1"
[ "${ID}" == "ubuntu" ] && os="2"
case $os in
    1)
        # Rocky Linux 9配置
        echo "当前操作系统是: Rocky Linux 9, 选择镜像源:"
        echo "1) 阿里云"
        echo "2) 上海交大"
        echo "3) 南京大学"
        read -p "输入选择(1/2/3): " mirror

        [ "$mirror" -eq 1 ] && url="mirrors.aliyun.com/rockylinux"
        [ "$mirror" -eq 2 ] && url="mirrors.sjtug.sjtu.edu.cn/rocky"
        [ "$mirror" -eq 3 ] && url="mirror.nju.edu.cn/rocky"
        [ -z "$url" ] && { echo "无效选择"; exit 1; }

        # 备份并配置源
        mkdir -p /etc/yum.repos.d/backup
        mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/
        cat > /etc/yum.repos.d/rocky.repo <<EOF
[baseos]
name=Rocky Linux BaseOS from $url
# mirrorlist=http://mirrors.rockylinux.org/mirrorlist/\$releasever/BaseOS/\$basearch
baseurl=https://$url/\$releasever/BaseOS/\$basearch/os/
enabled=1
gpgcheck=0

[appstream]
name=Rocky Linux AppStream $url
# mirrorlist=http://mirrors.rockylinux.org/mirrorlist/\$releasever/AppStream/\$basearch
baseurl=https://$url/\$releasever/AppStream/\$basearch/os/
enabled=1
gpgcheck=0

[extras]
name=Rocky Linux Extras $url
# mirrorlist=http://mirrors.rockylinux.org/mirrorlist/\$releasever/Extras/\$basearch
baseurl=https://$url/\$releasever/extras/\$basearch/os/
enabled=1
gpgcheck=0
EOF
        ;;
    2)
        # Ubuntu 24.04配置
        echo "当前操作系统是: Ubuntu 24.04, 选择镜像源:"
        echo "1) 阿里云"
        echo "2) 清华源"
        echo "3) 南京大学"
        read -p "输入选择(1/2/3): " mirror
        read -p "是否需要src源(yes|no): " srctype
        [ "$mirror" -eq 1 ] && url="mirrors.aliyun.com"
        [ "$mirror" -eq 2 ] && url="mirrors.tuna.tsinghua.edu.cn"
        [ "$mirror" -eq 3 ] && url="mirror.nju.edu.cn"
        [ -z "$url" ] && { echo "无效选择"; exit 1; }

        # 备份并配置源
        cp /etc/apt/sources.list /etc/apt/sources.list.bak
        rm -rf /etc/apt/sources.list.d/*
        cat > /etc/apt/sources.list <<EOF
        $(for repo in "" "-updates" "-backports" "-security"; do
          echo "deb http://$url/ubuntu/ noble${repo} main restricted universe multiverse"
          [ "${srctype}" == "yes" ] && echo "deb-src http://$url/ubuntu/ noble${repo} main restricted universe multiverse"
        done)
EOF
        apt-get update
        ;;
    *)
        echo "无效选择"
        exit 1
        ;;
esac

echo "配置完成!"